import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserMessageMapping } from './entities/user-message-mapping.entity';

@Injectable()
export class MessageService {
  private readonly logger = new Logger(MessageService.name);

  constructor(
    @InjectRepository(UserMessageMapping)
    private userMessageMappingRepository: Repository<UserMessageMapping>,
  ) {}

  // 获取腾讯云通信ID（不使用数据库）
  getTencentUserIdWithoutDB(userId: number): string {
    return `user_${userId}`;
  }

  // 保存用户ID与腾讯云通信ID的映射关系
  async saveUserMapping(userId: number, tencentUserId: string): Promise<void> {
    try {
      let mapping = await this.userMessageMappingRepository.findOne({
        where: { userId }
      });
      
      if (mapping) {
        // 如果映射已存在，更新它
        mapping.tencentUserId = tencentUserId;
        await this.userMessageMappingRepository.save(mapping);
        this.logger.log(`更新用户映射: userId=${userId}, tencentUserId=${tencentUserId}`);
      } else {
        // 如果映射不存在，创建新的
        mapping = this.userMessageMappingRepository.create({
          userId,
          tencentUserId
        });
        await this.userMessageMappingRepository.save(mapping);
        this.logger.log(`创建用户映射: userId=${userId}, tencentUserId=${tencentUserId}`);
      }
    } catch (error) {
      this.logger.error(`保存用户映射失败: ${error.message}`, error.stack);
      // 不抛出异常，允许程序继续执行
    }
  }

  // 获取用户的腾讯云通信ID
  async getTencentUserId(userId: number): Promise<string> {
    try {
      const mapping = await this.userMessageMappingRepository.findOne({
        where: { userId }
      });
      
      if (!mapping) {
        // 如果映射不存在，返回默认格式的ID
        const defaultId = this.getTencentUserIdWithoutDB(userId);
        this.logger.log(`用户映射不存在，使用默认ID: userId=${userId}, defaultId=${defaultId}`);
        return defaultId;
      }
      
      this.logger.log(`获取用户映射: userId=${userId}, tencentUserId=${mapping.tencentUserId}`);
      return mapping.tencentUserId;
    } catch (error) {
      this.logger.error(`获取用户映射失败: ${error.message}`, error.stack);
      // 如果出错，返回默认格式的ID
      return this.getTencentUserIdWithoutDB(userId);
    }
  }

  // 获取消息列表
  async getMessageList(userId: number, conversationID: string, count: number, lastMessageID?: string) {
    // 实现获取消息列表的逻辑
    return {
      messages: [],
      isCompleted: true
    };
  }

  // 发送消息
  async sendMessage(userId: number, messageData: any) {
    // 实现发送消息的逻辑
    return {
      messageId: 'msg_' + Date.now(),
      timestamp: new Date().toISOString()
    };
  }

  // 获取会话列表
  async getConversationList(userId: number) {
    // 实现获取会话列表的逻辑
    return {
      conversations: []
    };
  }

  // 创建群组
  async createGroup(userId: number, groupData: any) {
    // 实现创建群组的逻辑
    return {
      groupId: 'group_' + Date.now(),
      name: groupData.name
    };
  }

  // 加入群组
  async joinGroup(userId: number, groupID: string) {
    // 实现加入群组的逻辑
    return {
      success: true
    };
  }

  // 退出群组
  async quitGroup(userId: number, groupID: string) {
    // 实现退出群组的逻辑
    return {
      success: true
    };
  }

  // 获取群组成员
  async getGroupMembers(groupID: string) {
    // 实现获取群组成员的逻辑
    return {
      members: []
    };
  }
}

